<script lang="ts" setup>
  import { GameSingleReward } from '@/types/game-single-reward';
  import { onMounted, ref } from 'vue';
  import { createReward, updateReward } from '@/api/game-single-reward';
  import { Form, Message } from '@arco-design/web-vue';

  const props = defineProps<{
    gameId: string;
    courseId: string;
    singleReward?: GameSingleReward;
  }>();

  const emit = defineEmits(['close']);

  const data = ref<Partial<GameSingleReward>>({});

  onMounted(async () => {
    if (props.singleReward) {
      data.value = {
        ...props.singleReward,
      };
    } else {
      data.value.gameId = props.gameId;
      data.value.count = 1;
    }
  });

  const saving = ref(false);
  const formRef = ref<InstanceType<typeof Form> | null>(null);
  const handleSubmit = async () => {
    if (formRef.value) {
      const validate = await formRef.value.validate();
      if (!validate) {
        try {
          saving.value = true;
          if (!props.singleReward) {
            await createReward(data.value);
          } else {
            await updateReward(props.singleReward.id, data.value);
          }
          emit('close', true);
          Message.success('操作成功');
        } finally {
          saving.value = false;
        }
      }
    }
  };
</script>

<template>
  <a-modal
    :title="`${singleReward ? '编辑' : '添加'}单项奖`"
    :width="500"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <a-form ref="formRef" :model="data" layout="vertical">
      <a-form-item
        label="单项奖名称"
        field="name"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-input v-model="data.name" />
      </a-form-item>
      <a-form-item
        label="单项奖个数"
        field="count"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-input-number
          v-model="data.count"
          :precision="0"
          :min="1"
          :step="1"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
